import UserCodeCaptcha from '@/components/UserCodeCaptcha';
import type { UserRecord } from '@/DatabaseType/User';
import { updateUserPassword } from '@/services/user';
import type { RequestResult } from '@/utils/request';
import { ResponseCode } from '@/utils/request';
import { LockOutlined } from '@ant-design/icons';
import { ProFormText } from '@ant-design/pro-components';
import { Button, Card, Form, message, Tabs } from 'antd';
import React, { useState } from 'react';
import { useModel } from '@umijs/max';

enum ModifyWay {
  OldPassword = 'OldPassword',
  EmailCode = 'EmailCode',
}

interface Props {
  cardStyle?: React.CSSProperties;
}

const InformationPassword: React.FC<Props> = ({ cardStyle }) => {
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser as UserRecord;
  const [formInstance] = Form.useForm();
  const [loading, setLoading] = useState(false);

  // 提交
  async function handleSubmit() {
    const values = await formInstance.validateFields();
    const activeKey = values.activeKey as ModifyWay;
    setLoading(true);
    try {
      let requestResult: RequestResult<null>;
      switch (activeKey) {
        case ModifyWay.OldPassword: {
          requestResult = await updateUserPassword({
            email: currentUser.email,
            password: values.password,
            oldPassword: values.oldPassword,
          });
          break;
        }
        case ModifyWay.EmailCode: {
          requestResult = await updateUserPassword({
            email: currentUser.email,
            password: values.password,
            code: values.code,
          });
          break;
        }
      }
      message[requestResult.code === ResponseCode.Fail ? 'error' : 'success']({
        content: requestResult.message,
      });
      formInstance.resetFields();
    } catch (error) {
      console.log(
        'UserInfoManagement => InformationPassword => updateUserPassword',
        '请求失败',
      );
    }
    setLoading(false);
  }

  return (
    <Card title="密码管理" style={cardStyle}>
      <Form
        labelCol={{ span: 4 }}
        labelAlign="left"
        style={{ width: '50%' }}
        form={formInstance}
      >
        <Form.Item
          noStyle
          valuePropName="activeKey"
          name="activeKey"
          initialValue={ModifyWay.OldPassword}
        >
          <Tabs
            destroyInactiveTabPane={true}
            items={[
              {
                label: '旧密码',
                key: ModifyWay.OldPassword,
                children: (
                  <>
                    <ProFormText.Password
                      label="旧密码"
                      name="oldPassword"
                      fieldProps={{
                        prefix: <LockOutlined />,
                        autoComplete: 'current-password',
                      }}
                      placeholder="请输入旧密码"
                      rules={[
                        {
                          required: true,
                          message: '请输入旧密码!',
                        },
                      ]}
                    />
                    <ProFormText.Password
                      label="新密码"
                      name="password"
                      fieldProps={{
                        prefix: <LockOutlined />,
                        autoComplete: 'new-password',
                      }}
                      placeholder="请输入新密码"
                      rules={[
                        {
                          required: true,
                          message: '请输入新密码!',
                        },
                      ]}
                    />
                  </>
                ),
              },
              {
                label: '邮箱',
                key: ModifyWay.EmailCode,
                children: (
                  <>
                    <ProFormText
                      label="邮箱"
                      name="email"
                      rules={[
                        {
                          required: true,
                          message: '请输入邮箱!',
                        },
                      ]}
                      placeholder="请输入邮箱"
                    />
                    <ProFormText.Password
                      label="新密码"
                      name="password"
                      fieldProps={{
                        prefix: <LockOutlined />,
                        autoComplete: 'new-password',
                      }}
                      rules={[
                        {
                          required: true,
                          message: '请输入邮箱!',
                        },
                      ]}
                      placeholder="请输入新密码"
                    />
                    <UserCodeCaptcha formInstance={formInstance} />
                  </>
                ),
              },
            ]}
          />
        </Form.Item>
      </Form>
      <Button type="primary" onClick={handleSubmit} loading={loading}>
        更新
      </Button>
    </Card>
  );
};

export default InformationPassword;
